package cn.lanqiao.bigDate.web.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;
import cn.lanqiao.common.utils.TokenUtil;

import cn.lanqiao.bigDate.web.BaseController;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import cn.lanqiao.bigDate.web.security.Security;
import cn.lanqiao.bigDate.service.sys.LoginService;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class LoginController extends BaseController {

	@Autowired
	private LoginService loginService;

	@RequestMapping("/toLogin")
	public String login(){
		return "main/login";
	}

	@RequestMapping("/doLogin")
	public @ResponseBody void login(@RequestBody Map<String,String> body,HttpServletResponse res) throws IOException {
		String verifyTime=body.get("vertifyTime");
		String safeCode=body.get("safecode");
		String safeCodeTarget=stringRedisTemplate.opsForValue().get(verifyTime);
		if(safeCodeTarget==null||safeCodeTarget.trim().equals("")){
			res.setStatus(401);
			return;
		}
		System.out.println(safeCode);
		System.out.println(safeCodeTarget);
		if(!safeCode.toUpperCase().equals(safeCodeTarget.toUpperCase())){
			res.setStatus(402);
			return;
		}
		stringRedisTemplate.delete(verifyTime);
		String username=body.get("username");
		String password=body.get("password");
		String loginIp= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getRemoteAddr();
		boolean logined=loginService.login(username,password,loginIp);
		if(logined){
			loginService.getMenuList(username);
			//res.setHeader("Authorization","Bearer "+TokenUtil.sign(username,""));
			res.setStatus(200);
			Cookie authorization = new Cookie("Authorization", URLEncoder.encode("Bearer " + TokenUtil.sign(username, "")));
			authorization.setPath("/bigDateWeb");
			authorization.setMaxAge(15*60);
			res.addCookie(authorization);
		}else{
			res.setStatus(404);
		}
	}
	@RequestMapping("/invalidate")
	public String invalidate(){
		return "main/invalidate";
	}
	@RequestMapping("/expires")
	public String expires(){
		return "main/expires";
	}
	@RequestMapping("/logout")
	public @ResponseBody void logout(){
		
	}
}